package com.lzj.friend;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FriendTopN {
    public static void main(String[] args) throws IOException {
        //加载HDFS的配置信息
        Configuration configuration = new Configuration(true);
        //获取HDFS的文件系统
        FileSystem fileSystem = FileSystem.get(configuration);
        //获取要操作的资源路径
        Path path = new Path("/lzj/result/friend-1604912071611/part-r-00000");
        //开始读取数据
        List<String> recommendedList = IOUtils.readLines(fileSystem.open(path));
        //创建推荐关系列表
        Map<String, Map<String, Integer>> recommendedMap = new HashMap<>();

        //开始解析 郑耀晨:张家辉	3
        for (String recommended : recommendedList) {
            //首先解析好友推荐度
            String[] ss1 = recommended.split("\\s+");
            //解析好友列表
            String[] fs = ss1[0].split(":");
            //获取数据
            String f1 = fs[0];
            String f2 = fs[1];
            int rcnum = Integer.parseInt(ss1[1]);
            //将f2加入到f1的推荐列表
            if (!recommendedMap.containsKey(f1)) {
                recommendedMap.put(f1, new HashMap<>());
            }
            recommendedMap.get(f1).put(f2, rcnum);

            //将f1加入到f2的推荐列表
            if (!recommendedMap.containsKey(f2)) {
                recommendedMap.put(f2, new HashMap<>());
            }
            recommendedMap.get(f2).put(f1, rcnum);
        }
        //依次排序每个用户的TopN
        for (String student : recommendedMap.keySet()) {
            //重新排序好友推荐
            Map<String, Integer> sortMap = recommendedMap.get(student)
                    .entrySet().stream()
                    .filter(e -> e.getValue() > 5)
                    .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                    .limit(5)
                    .collect(Collectors.toMap(Map.Entry::getKey,
                            Map.Entry::getValue, (oldVal, newVal) -> oldVal,
                            LinkedHashMap::new));
            //将其重新添加到Map
            recommendedMap.put(student, sortMap);
        }
        //打印最终的推荐信息
        for (String s : recommendedMap.keySet()) {
            System.out.println(s + "----" + recommendedMap.get(s));
        }

    }

}
